package hello.base;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


// 获取spring容器中已经注入的bean的工具类
@Component
public class SpringContextUtil implements ApplicationContextAware {

    // 日志
    private static final Logger log = LoggerFactory.getLogger(SpringContextUtil.class);

    // 实现了的Bean工厂ApplicationContext
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        log.info("ApplicationContext初始化完成." );
        SpringContextUtil.applicationContext = applicationContext;
    }

    // 获取上下文中已经被加载了的Bean
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
}
